#tool_user_zhanneixin工具 站内信
from django.shortcuts import render, redirect,get_object_or_404,HttpResponse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView,FormView
from django.contrib.auth.mixins import LoginRequiredMixin

from .forms import tool_BeiWang_Form,tool_zhanneixin_Form
from django.http import HttpResponseBadRequest
from KeHu.models import KeHu
from django.contrib.auth.models import User
from .models import tool_user_zhanneixin, tool_zhanneixin_zhuangtai
import logging



class tool_user_zhanneixin(LoginRequiredMixin, ListView):
    model = tool_user_zhanneixin
    template_name = 'tool_user_zhanneixin_list.html'
    context_object_name = 'beiwangs'
    paginate_by = 10


class tool_user_zhanneixinDetail(LoginRequiredMixin,DetailView):
    model = tool_user_zhanneixin
    template_name = 'tool_user_zhanneixin_detail.html'
    context_object_name = 'beiwangs'

class tool_user_zhanneixinCreate(LoginRequiredMixin,CreateView):
    model = tool_user_zhanneixin
    success_url = '/tool_user_zhanneixin/'
    template_name = 'tool_user_zhanneixin_add.html'
    form_class = tool_zhanneixin_Form


  #  form_class = tool_BeiWang_Form
    def form_valid(self, form):
        self.object = form.save(commit=False)
        adduser = self.request.user
        print(adduser)
        self.object.add_user = adduser
        self.object.save()
        return super().form_valid(form)

class tool_user_zhanneixinDelete(LoginRequiredMixin,DeleteView):
    model = tool_user_zhanneixin
    success_url = '/beiwang/'
    template_name = 'tool_user_zhanneixin_add.html'

    def get(self, request, pk, *args, **kwargs):
        beiwang = get_object_or_404(tool_user_zhanneixin, pk=pk)
        if beiwang.add_user == request.user:
            return super().delete(request, pk, *args, **kwargs)
        else:
            return redirect('/')


def zhanneixin_index(message_title, receiver_id, fasongren_id):
    # 使用 get_object_or_404 来获取 User 实例，确保用户存在
    receiver = get_object_or_404(User, receiver_id)
    fasongren = get_object_or_404(User, fasongren_id)
    # 使用 get_object_or_404 来获取 User 实例，确保用户存在
    # receiver = get_object_or_404(User, id=receiver_id)
    # fasongren = get_object_or_404(User, id=fasongren_id)
    try:
        # 创建通知实例
        notification = tool_user_zhanneixin.objects.create(
            title="系统消息",
            content=message_title,
            add_user=fasongren,
        )
        # 添加接收人到通知的接收人列表中
        notification.jieshouren.add(receiver)
        # 创建通知状态实例
        # 注意：这里假设 add_user 应该是发送通知的用户（fasongren）
        tool_zhanneixin_zhuangtai.objects.create(
            xinxi=notification,
            zhaungtai='未读',  # 使用具体的值而不是变量名作为默认
            add_user=fasongren,  # 修改为发送通知的用户
        )
        return HttpResponse("通知已成功发送")
    except Exception as e:
        # 记录异常
        logger = logging.getLogger(__name__)
        logger.error("在创建通知时发生错误", exc_info=True)
        return HttpResponseBadRequest("在创建通知时发生错误，请稍后再试。")